package com.hulman.oms.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

/**
 * @Author: maxwellens
 */
public class JwtUtil
{
    /**
     * 1天的毫秒数
     */

    public static final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000;

    /**
     * 默认90天有效期
     */
    private static final long DEFAULT_EXPIRE_TIME = 90 * MILLIS_PER_DAY;

    /**
     * 校验token是否正确
     *
     * @param token           令牌
     * @param username        登录名
     * @param encodedPassword 加密的密码
     * @return
     */
    public static boolean verify(String token, String username, String encodedPassword)
    {
        try
        {
            Algorithm algorithm = Algorithm.HMAC256(encodedPassword);
            JWTVerifier verifier = JWT.require(algorithm).withClaim("username", username).build();
            try
            {
                verifier.verify(token);
                return true;
            } catch (Exception ex)
            {
                return false;
            }

        } catch (Exception e)
        {
            return false;
        }
    }

    /**
     * 生成JWT签名（默认有效期）
     *
     * @param username
     * @param encodedPassword
     * @return
     */
    public static String sign(String username, String encodedPassword)
    {
        return sign(username, encodedPassword, DEFAULT_EXPIRE_TIME);
    }

    /**
     * 生成JWT签名
     *
     * @param username        用户名
     * @param encodedPassword 加密的密码
     * @param expireTime      有效期
     * @return
     */
    public static String sign(String username, String encodedPassword, long expireTime)
    {
        // 指定过期时间
        Date date = new Date(System.currentTimeMillis() + expireTime);
        Algorithm algorithm = Algorithm.HMAC256(encodedPassword);
        return JWT.create().withClaim("username", username).withExpiresAt(date).sign(algorithm);
    }

    /**
     * 获取登录名
     *
     * @param token
     * @return
     */
    public static String getUsername(String token)
    {
        if (StringUtil.isEmpty(token))
        {
            return null;
        }
        try
        {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("username").asString();
        } catch (JWTDecodeException e)
        {
            return null;
        }
    }

    public static void main(String[] args)
    {
        String username = "admin";
        String password = "12345678";
        //String encodedPassword = CipherUtil.encrypt(username, password);
        String jwt = JwtUtil.sign("admin", password);
        System.out.println(jwt);
        boolean result = JwtUtil.verify(jwt, username, password);
        System.out.println(result);
    }
}